package com.example.socialapp.ui.chat

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.absoluteValue
import kotlinx.coroutines.delay

/**
 * 聊天详情界面
 *
 * @param chatId 聊天ID
 * @param chatName 聊天名称
 * @param onNavigateBack 返回上一界面回调
 * @param onNavigateToProfile 导航到对方资料界面回调
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatDetailScreen(
    chatId: String,
    chatName: String,
    onNavigateBack: () -> Unit,
    onNavigateToProfile: () -> Unit = {}
) {
    var messageText by remember { mutableStateOf("") }
    var showMenu by remember { mutableStateOf(false) }
    
    // 示例消息列表
    val messages = remember { generateSampleMessages() }
    val listState = rememberLazyListState()
    
    // 首次加载时滚动到最后一条消息
    LaunchedEffect(Unit) {
        if (messages.isNotEmpty()) {
            listState.scrollToItem(messages.size - 1)
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { 
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.clickable { onNavigateToProfile() }
                    ) {
                        Text(chatName)
                    }
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = { /* 查看聊天详情 */ }) {
                        Icon(
                            imageVector = Icons.Default.Info,
                            contentDescription = "聊天信息"
                        )
                    }
                    IconButton(onClick = { showMenu = true }) {
                        Icon(
                            imageVector = Icons.Default.MoreVert,
                            contentDescription = "更多选项"
                        )
                        DropdownMenu(
                            expanded = showMenu,
                            onDismissRequest = { showMenu = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text("清空聊天记录") },
                                onClick = { 
                                    showMenu = false
                                    /* 清空聊天记录逻辑 */ 
                                }
                            )
                            DropdownMenuItem(
                                text = { Text("举报") },
                                onClick = { 
                                    showMenu = false
                                    /* 举报逻辑 */ 
                                }
                            )
                            DropdownMenuItem(
                                text = { Text("加入黑名单") },
                                onClick = { 
                                    showMenu = false
                                    /* 黑名单逻辑 */ 
                                }
                            )
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        },
        bottomBar = {
            ChatInputBar(
                value = messageText,
                onValueChange = { messageText = it },
                onSendClick = {
                    if (messageText.isNotBlank()) {
                        // 发送消息逻辑（在实际应用中应与ViewModel交互）
                        messageText = ""
                    }
                }
            )
        }
    ) { innerPadding ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .padding(horizontal = 16.dp),
            state = listState,
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(messages) { message ->
                ChatMessageItem(message = message)
            }
        }
    }
}

/**
 * 聊天输入栏
 */
@Composable
private fun ChatInputBar(
    value: String,
    onValueChange: (String) -> Unit,
    onSendClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(0.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 8.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            IconButton(onClick = { /* 添加附件 */ }) {
                Icon(
                    imageVector = Icons.Default.AttachFile,
                    contentDescription = "添加附件"
                )
            }
            
            OutlinedTextField(
                value = value,
                onValueChange = onValueChange,
                modifier = Modifier.weight(1f),
                placeholder = { Text("输入消息...") },
                keyboardOptions = KeyboardOptions(
                    capitalization = KeyboardCapitalization.Sentences,
                    keyboardType = KeyboardType.Text,
                    imeAction = ImeAction.Send
                ),
                keyboardActions = KeyboardActions(
                    onSend = { onSendClick() }
                ),
                maxLines = 3,
                shape = RoundedCornerShape(24.dp)
            )
            
            Spacer(modifier = Modifier.width(4.dp))
            
            // 语音按钮
            IconButton(onClick = { /* 录音功能 */ }) {
                Icon(
                    imageVector = Icons.Default.Mic,
                    contentDescription = "语音消息"
                )
            }
            
            // 发送按钮
            IconButton(
                onClick = onSendClick,
                enabled = value.isNotBlank()
            ) {
                Icon(
                    imageVector = Icons.Default.Send,
                    contentDescription = "发送",
                    tint = if (value.isNotBlank()) 
                        MaterialTheme.colorScheme.primary 
                    else 
                        MaterialTheme.colorScheme.outline
                )
            }
        }
    }
}

/**
 * 聊天消息项
 */
@Composable
private fun ChatMessageItem(message: ChatMessage) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalAlignment = if (message.isFromMe) Alignment.End else Alignment.Start
    ) {
        Row(
            verticalAlignment = Alignment.Top,
            horizontalArrangement = if (message.isFromMe) Arrangement.End else Arrangement.Start,
            modifier = Modifier.fillMaxWidth()
        ) {
            // 如果不是自己发的消息，显示头像
            if (!message.isFromMe) {
                Avatar(name = message.senderName)
                Spacer(modifier = Modifier.width(8.dp))
            }
            
            Column(
                horizontalAlignment = if (message.isFromMe) Alignment.End else Alignment.Start
            ) {
                // 如果不是自己发的消息，显示发送者名称
                if (!message.isFromMe) {
                    Text(
                        text = message.senderName,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline,
                        modifier = Modifier.padding(start = 4.dp, bottom = 2.dp)
                    )
                }
                
                // 消息气泡
                Card(
                    shape = RoundedCornerShape(
                        topStart = if (message.isFromMe) 16.dp else 4.dp,
                        topEnd = if (message.isFromMe) 4.dp else 16.dp,
                        bottomStart = 16.dp,
                        bottomEnd = 16.dp
                    ),
                    colors = CardDefaults.cardColors(
                        containerColor = if (message.isFromMe) 
                            MaterialTheme.colorScheme.primaryContainer
                        else 
                            MaterialTheme.colorScheme.secondaryContainer
                    ),
                    modifier = Modifier.widthIn(max = 280.dp)
                ) {
                    Text(
                        text = message.content,
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.padding(12.dp)
                    )
                }
                
                // 消息时间
                Text(
                    text = message.formattedTime,
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.outline,
                    modifier = Modifier.padding(top = 2.dp, start = 4.dp, end = 4.dp)
                )
            }
            
            // 如果是自己发的消息，显示头像
            if (message.isFromMe) {
                Spacer(modifier = Modifier.width(8.dp))
                Avatar(name = "我")
            }
        }
    }
}

/**
 * 头像组件
 */
@Composable
private fun Avatar(name: String) {
    Box(
        modifier = Modifier
            .size(36.dp)
            .clip(CircleShape)
            .background(getColorForName(name)),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = name.first().toString(),
            style = MaterialTheme.typography.bodyLarge,
            color = Color.White
        )
    }
}

/**
 * 根据名称生成颜色
 */
private fun getColorForName(name: String): Color {
    val colors = listOf(
        Color(0xFF6200EA), // 深紫色
        Color(0xFF2962FF), // 深蓝色
        Color(0xFF00BFA5), // 青色
        Color(0xFFFFAB00), // 琥珀色
        Color(0xFFD50000)  // 红色
    )
    
    return colors[name.hashCode().mod(colors.size).absoluteValue]
}

/**
 * 聊天消息数据类
 */
data class ChatMessage(
    val id: String,
    val content: String,
    val timestamp: Long,
    val senderName: String,
    val isFromMe: Boolean
) {
    val formattedTime: String
        get() {
            val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
            return sdf.format(Date(timestamp))
        }
}

/**
 * 生成示例消息数据
 */
private fun generateSampleMessages(): List<ChatMessage> {
    val currentTime = System.currentTimeMillis()
    val hourInMillis = 60 * 60 * 1000L
    
    return listOf(
        ChatMessage(
            id = "1",
            content = "你好，最近在忙什么？",
            timestamp = currentTime - 5 * hourInMillis,
            senderName = "张三",
            isFromMe = false
        ),
        ChatMessage(
            id = "2",
            content = "我在准备一个项目的演示，下周要进行汇报",
            timestamp = currentTime - 4 * hourInMillis,
            senderName = "我",
            isFromMe = true
        ),
        ChatMessage(
            id = "3",
            content = "听起来很有挑战性！需要帮忙吗？",
            timestamp = currentTime - 4 * hourInMillis + 5 * 60 * 1000,
            senderName = "张三",
            isFromMe = false
        ),
        ChatMessage(
            id = "4",
            content = "谢谢你的好意，我目前应该能够处理好。不过如果你有关于数据可视化的建议，我很乐意听听",
            timestamp = currentTime - 3 * hourInMillis,
            senderName = "我",
            isFromMe = true
        ),
        ChatMessage(
            id = "5",
            content = "我有一些资料可以分享给你，包括一些关于数据可视化的最佳实践和案例研究",
            timestamp = currentTime - 2 * hourInMillis,
            senderName = "张三",
            isFromMe = false
        ),
        ChatMessage(
            id = "6",
            content = "太好了！这正是我需要的",
            timestamp = currentTime - 1 * hourInMillis,
            senderName = "我",
            isFromMe = true
        ),
        ChatMessage(
            id = "7",
            content = "我稍后会发送给你，另外，周末有空一起去参加那个技术讲座吗？",
            timestamp = currentTime - 30 * 60 * 1000,
            senderName = "张三",
            isFromMe = false
        ),
        ChatMessage(
            id = "8",
            content = "应该没问题，是周六下午那个关于人工智能的讲座吗？",
            timestamp = currentTime - 15 * 60 * 1000,
            senderName = "我",
            isFromMe = true
        ),
        ChatMessage(
            id = "9",
            content = "是的，正是那个。到时候我们可以一起去，讲座结束后还可以讨论一下你的项目",
            timestamp = currentTime - 10 * 60 * 1000,
            senderName = "张三",
            isFromMe = false
        ),
        ChatMessage(
            id = "10",
            content = "好的，周六见！",
            timestamp = currentTime - 5 * 60 * 1000,
            senderName = "我",
            isFromMe = true
        )
    )
} 